<template>
  <div class="sliderx" ref="sliderx">
    <div class="sliderx-group" ref="sliderxGroup">
      <slot></slot>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import {addClass} from "../../common/js/dom";
  import BScroll from 'better-scroll'

  export default {
    props: {
      probeType: {
        type: Number,
        default: 1
      },
      listenScroll: {
        type: Boolean,
        default: false
      },
      childrenWidth: {
        type: Number,
        default: 1
      }
    },
    data () {
      return {
      }
    },
    mounted () {
      setTimeout(() => {
        this._setSliderWidth()
        this._initSlider()
      }, 20)

      window.addEventListener('resize', () => {
        if (!this.slider) {
          return
        }
        this._setSliderWidth(true)
        this.slider.refresh()
      })
    },
    deactivated () {

    },
    beforeDestroy () {

    },
    methods: {
      // 因为是横向滚动，需计算slide 的宽度并且赋值
      _setSliderWidth (isResize) {
        let children = this.$refs.sliderxGroup.children  // 获取整个列表有多少个元素
        let width = 0 // 总的宽度
        let sliderWidth = this.$refs.sliderx.clientWidth/this.childrenWidth // slide 父元素的宽度
        for (let i = 0; i < children.length; i++) {
          let child = children[i] // 获取每个子元素
          // addClass(child, 'sliderx-item') // 添加名为slider-item的类名

          child.style.width = sliderWidth + 'px'
          width += sliderWidth
        }
        if (this.loop && !isResize) { // 如果slide是需要循环的话，slide会在左右两侧copy两个子元素从而保证循环切换
          width += 2 * sliderWidth
        }
        this.$refs.sliderxGroup.style.width = width + 'px'
      },
      _initSlider () { // 初始化slide
        this.slider = new BScroll(this.$refs.sliderx, {
          scrollX: true,  // 横向滚动
          scrollY: false, // 不允许纵向滚动
          momentum: false,// 是否开启动量动画，关闭可以提升效率
          snap: true,
          probeType: this.probeType,
        })

        if (this.listenScroll) {
          let me = this
          this.slider.on('scroll', (pos) => {
            me.$emit('scroll', pos)
          })
        }

        this.slider.on('scrollEnd', () => {
          // 参考文档 https://ustbhuangyi.github.io/better-scroll/doc/zh-hans/api-specific.html#getcurrentpage
          let pageIndex = this.slider.getCurrentPage().pageX

          this.$emit('indexPage', pageIndex)
        })
      },
      refresh () {
        this.slider && this.slider.refresh()
      }
    },
    watch: {
    }
  }
</script>

<style lang="scss">
  .sliderx{
    min-height: 1px;
    position: relative;
    .sliderx-group{
      position: relative;
      overflow: hidden;
      white-space: nowrap;
      height: 100%;
      .sliderx-item{
        box-sizing: border-box;
        overflow: hidden;
        /*img{*/
          /*display: block;*/
          /*width: 100%;*/
          /*height: 100%;*/
        /*}*/
      }
    }
  }
</style>
